#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
详细测试30秒无沟通自动转回AI功能
"""

import time
from datetime import datetime, timedelta
from handlers.conversation_manager import ConversationManager

def test_30s_auto_switch_detailed():
    """详细测试30秒无沟通自动转回AI功能"""
    print("🧪 详细测试30秒无沟通自动转回AI功能...")
    print("=" * 60)
    
    # 创建对话管理器
    manager = ConversationManager()
    customer_id = "test_customer_detailed"
    
    print(f"📝 测试客户ID: {customer_id}")
    
    # 1. 初始状态检查
    print("\n1️⃣ 初始状态检查")
    session_info = manager.get_session_info(customer_id)
    print(f"   🤖 是否人工服务: {session_info['is_human_service']}")
    print(f"   💬 最后沟通时间: {session_info['last_communication_time']}")
    print(f"   🔄 是否应该转回AI: {session_info['should_switch_back']}")
    
    # 2. 切换到人工服务
    print("\n2️⃣ 切换到人工服务")
    session = manager.switch_to_human_service(customer_id)
    print(f"   ✅ 已切换到人工服务")
    print(f"   📅 人工服务开始时间: {session.human_service_start}")
    print(f"   💬 初始沟通时间: {session.last_communication_time}")
    
    # 3. 检查切换后的状态
    print("\n3️⃣ 检查切换后的状态")
    session_info = manager.get_session_info(customer_id)
    print(f"   🤖 是否人工服务: {session_info['is_human_service']}")
    
    time_since_last = session_info['time_since_last_communication']
    if time_since_last is not None:
        print(f"   ⏰ 距离上次沟通: {time_since_last:.1f}秒")
    else:
        print(f"   ⏰ 距离上次沟通: 无")
    
    print(f"   🔄 是否应该转回AI: {session_info['should_switch_back']}")
    
    # 4. 模拟客户发送消息
    print("\n4️⃣ 模拟客户发送消息")
    manager.add_customer_message(customer_id, "你好，我需要帮助")
    session_info = manager.get_session_info(customer_id)
    print(f"   ✅ 客户消息已添加")
    
    time_since_last = session_info['time_since_last_communication']
    if time_since_last is not None:
        print(f"   ⏰ 距离上次沟通: {time_since_last:.1f}秒")
    else:
        print(f"   ⏰ 距离上次沟通: 无")
    
    print(f"   🔄 是否应该转回AI: {session_info['should_switch_back']}")
    
    # 5. 等待10秒后检查
    print("\n5️⃣ 等待10秒后检查")
    time.sleep(10)
    session_info = manager.get_session_info(customer_id)
    
    time_since_last = session_info['time_since_last_communication']
    if time_since_last is not None:
        print(f"   ⏰ 距离上次沟通: {time_since_last:.1f}秒")
    else:
        print(f"   ⏰ 距离上次沟通: 无")
    
    print(f"   🔄 是否应该转回AI: {session_info['should_switch_back']}")
    
    # 6. 模拟客服回复
    print("\n6️⃣ 模拟客服回复")
    manager.update_communication_time(customer_id)
    session_info = manager.get_session_info(customer_id)
    print(f"   ✅ 客服回复时间已更新")
    
    time_since_last = session_info['time_since_last_communication']
    if time_since_last is not None:
        print(f"   ⏰ 距离上次沟通: {time_since_last:.1f}秒")
    else:
        print(f"   ⏰ 距离上次沟通: 无")
    
    print(f"   🔄 是否应该转回AI: {session_info['should_switch_back']}")
    
    # 7. 等待35秒后检查（应该自动转回AI）
    print("\n7️⃣ 等待35秒后检查（应该自动转回AI）")
    print("   ⏳ 开始等待35秒...")
    start_time = datetime.now()
    time.sleep(35)
    end_time = datetime.now()
    actual_wait_time = (end_time - start_time).total_seconds()
    print(f"   ⏰ 实际等待时间: {actual_wait_time:.1f}秒")
    
    session_info = manager.get_session_info(customer_id)
    
    time_since_last = session_info['time_since_last_communication']
    if time_since_last is not None:
        print(f"   ⏰ 距离上次沟通: {time_since_last:.1f}秒")
    else:
        print(f"   ⏰ 距离上次沟通: 无")
    
    print(f"   🔄 是否应该转回AI: {session_info['should_switch_back']}")
    
    # 8. 执行自动切换检查
    print("\n8️⃣ 执行自动切换检查")
    switched = manager.check_and_auto_switch(customer_id)
    if switched:
        print("   ✅ 已自动转回AI服务")
    else:
        print("   ❌ 未自动转回AI服务")
    
    # 9. 最终状态检查
    print("\n9️⃣ 最终状态检查")
    session_info = manager.get_session_info(customer_id)
    print(f"   🤖 是否人工服务: {session_info['is_human_service']}")
    print(f"   💬 最后沟通时间: {session_info['last_communication_time']}")
    
    # 处理可能为None的情况
    time_since_last = session_info['time_since_last_communication']
    if time_since_last is not None:
        print(f"   ⏰ 距离上次沟通: {time_since_last:.1f}秒")
    else:
        print(f"   ⏰ 距离上次沟通: 无（已转回AI服务）")
    
    print(f"   🔄 是否应该转回AI: {session_info['should_switch_back']}")
    
    # 10. 验证结果
    print("\n🔍 验证结果")
    if not session_info['is_human_service']:
        print("   ✅ 测试通过：已成功自动转回AI服务")
        return True
    else:
        print("   ❌ 测试失败：仍然在人工服务状态")
        return False

def test_communication_time_update():
    """测试沟通时间更新功能"""
    print("\n🧪 测试沟通时间更新功能...")
    print("=" * 40)
    
    manager = ConversationManager()
    customer_id = "test_customer_update"
    
    # 切换到人工服务
    manager.switch_to_human_service(customer_id)
    
    # 记录初始时间
    initial_info = manager.get_session_info(customer_id)
    initial_time = initial_info['last_communication_time']
    print(f"   📅 初始沟通时间: {initial_time}")
    
    # 等待5秒
    print("   ⏳ 等待5秒...")
    time.sleep(5)
    
    # 手动更新沟通时间
    manager.update_communication_time(customer_id)
    
    # 检查更新后的时间
    updated_info = manager.get_session_info(customer_id)
    updated_time = updated_info['last_communication_time']
    print(f"   📅 更新后沟通时间: {updated_time}")
    
    # 验证时间已更新
    if updated_time != initial_time:
        print("   ✅ 沟通时间更新成功")
        return True
    else:
        print("   ❌ 沟通时间更新失败")
        return False

def test_should_switch_back_logic():
    """测试should_switch_back_to_ai逻辑"""
    print("\n🧪 测试should_switch_back_to_ai逻辑...")
    print("=" * 40)
    
    manager = ConversationManager()
    customer_id = "test_customer_logic"
    
    # 1. 不在人工服务状态时
    print("1️⃣ 测试不在人工服务状态时")
    should_switch = manager.should_switch_back_to_ai(customer_id)
    print(f"   🔄 是否应该转回AI: {should_switch} (应该是False)")
    
    # 2. 切换到人工服务
    print("\n2️⃣ 切换到人工服务")
    manager.switch_to_human_service(customer_id)
    should_switch = manager.should_switch_back_to_ai(customer_id)
    print(f"   🔄 是否应该转回AI: {should_switch} (应该是False，因为刚切换)")
    
    # 3. 等待35秒后检查
    print("\n3️⃣ 等待35秒后检查")
    time.sleep(35)
    should_switch = manager.should_switch_back_to_ai(customer_id)
    print(f"   🔄 是否应该转回AI: {should_switch} (应该是True)")
    
    return should_switch

def main():
    """主测试函数"""
    print("🚀 开始详细测试30秒无沟通自动转回AI功能...")
    print("=" * 80)
    
    # 测试30秒自动切换
    test1_result = test_30s_auto_switch_detailed()
    
    # 测试沟通时间更新
    test2_result = test_communication_time_update()
    
    # 测试逻辑
    test3_result = test_should_switch_back_logic()
    
    print("\n" + "=" * 80)
    print("📋 测试总结:")
    print(f"   30秒自动切换测试: {'✅ 通过' if test1_result else '❌ 失败'}")
    print(f"   沟通时间更新测试: {'✅ 通过' if test2_result else '❌ 失败'}")
    print(f"   逻辑测试: {'✅ 通过' if test3_result else '❌ 失败'}")
    
    if test1_result and test2_result and test3_result:
        print("\n🎉 所有测试通过！30秒无沟通自动转回AI功能已正常工作")
    else:
        print("\n⚠️  部分测试失败，请检查代码实现")
        
        if not test1_result:
            print("   🔍 30秒自动切换测试失败，可能的原因：")
            print("      - 时间计算有误")
            print("      - 自动切换逻辑有问题")
            print("      - 会话状态更新有问题")
        
        if not test2_result:
            print("   🔍 沟通时间更新测试失败，可能的原因：")
            print("      - update_communication_time方法有问题")
            print("      - 时间字段更新有问题")
        
        if not test3_result:
            print("   🔍 逻辑测试失败，可能的原因：")
            print("      - should_switch_back_to_ai逻辑有问题")
            print("      - 时间比较有问题")

if __name__ == "__main__":
    main() 